#include "../include/Pipe.h"
#include "../include/LogSvr.h"
#include "../include/NDK.h"
#include "../include/ThreadManager.h"

typedef Singleton_T<LogSvr> log;
Pipe pipe_test;
THREAD_FUNC_RETURN_T read_func (void *arg)
{
    while (1)
    {
	int n = 0;
	if (NDK::handle_read_ready (pipe_test.read_handle ()) > 0)
	{
	    NDK::read_n (pipe_test.read_handle (), (void *)&n, sizeof(int), &TimeValue::zero);
	    log::instance ()->put (LOG_RINFO, "read int = %d\n", n);
	}else
	{
	    log::instance ()->put (LOG_RINFO, "select read ready failed");
	    break;
	}
    }
    return 0;
}
THREAD_FUNC_RETURN_T write_func (void *arg)
{
    int n = 0;
    const TimeValue tv(0, 5000);
    while (1)
    {
	NDK::sleep (&tv);
	NDK::write_n (pipe_test.write_handle (), (void *)&n, sizeof (n), 0);
	++n;
	if (n >= 1000000)
	    n = 0;
    }
    return 0;
}
int main ()
{
    log::instance ()->open ("log");
    if (pipe_test.open () != 0)
    {
	log::instance ()->put (LOG_RINFO, "open failed");
	return -1;
    }
    sleep (1);
    ThreadManager::instance ()->spawn (read_func);
    ThreadManager::instance ()->spawn (write_func);
    ThreadManager::instance ()->wait ();
    return 0;
}
